﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Gnosis.Alexandria.Controllers
{
    public abstract class ControllerBase : DispatcherBase
    {
        protected ControllerBase()
            : base()
        {
            
        }

        protected ControllerBase(IDispatcher parent)
            : base(parent)
        {
        }

        private readonly IDictionary<Type, IHandler> _handlers = new Dictionary<Type, IHandler>();

        protected void AddHandler<T>(IHandler<T> handler)
            where T : IMessage
        {
            if (handler == null)
                throw new ArgumentNullException("handler");

            _handlers.Add(typeof(T), handler);
        }

        protected void RemoveHandler<T>()
            where T : IMessage
        {
            if (_handlers.ContainsKey(typeof(T)))
                _handlers.Remove(typeof(T));
        }

        protected virtual void TryHandle<T>(T message)
            where T : IMessage
        {
            if (_handlers.ContainsKey(typeof(T)))
                ((IHandler<T>)_handlers[typeof (T)]).Handle(message);
        }
    }
}
